package com.ldc.commonlibs

import android.app.Application
import android.content.Context
import android.content.res.Configuration
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.uts.AppUtils
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout

abstract class BaseApplication : Application() {
    protected val TAG = "【%s】".format(this::class.java.name)

    private val clazzList: ArrayList<Class<out BaseAppInit>> = arrayListOf()
    private val appInitList: ArrayList<BaseAppInit> = arrayListOf()


    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(base)
    }

    override fun onCreate() {
        super.onCreate()
        appInit()
        registerARouter(this)
        initRefreshView()
        initCreate(this)
        AppUtils.INSTANCE.initSDK(this)
    }

    // 注册
    open fun register(clazz: Class<out BaseAppInit>) {
        clazzList.add(clazz)
    }

    // 注册ARouter
    open fun registerARouter(app: Application) {
        if (AppConf.isDebug) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(app)
    }

    protected abstract fun appInit()

    // 初始化一些配置项
    private fun initCreate(application: Application) {
        try {
            for (clazz: Class<out BaseAppInit> in clazzList) {
                val baseAppInit = clazz.newInstance()
                baseAppInit.setApplication(application)
                baseAppInit.onCreate()
                appInitList.add(baseAppInit)
            }
        } catch (e: InstantiationException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace();
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        for (app in appInitList) {
            app.configurationChanged(newConfig)
        }
    }

    override fun onLowMemory() {
        super.onLowMemory()
        for (app in appInitList) {
            app.onLowMemory()
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        for (app in appInitList) {
            app.onTerminate()
        }
    }


    // 设置默认SmartRefreshView
    private fun initRefreshView() {
        // 设置默认头
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            MaterialHeader(context)
        }
        // 设置
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            ClassicsFooter(context)
        }
    }

}